import React from 'react';
import {
  View,
  StyleSheet,
  Image,
  Text,
  SafeAreaView,
  TouchableOpacity,
  DeviceEventEmitter,
  BackHandler,
  InteractionManager,
  NativeModules
} from 'react-native';
import { iconWlSource, iconWlSourceGray, iconWlAdd, empty01 } from '../../../../image';
import { BackImage, msg, Header, _, XMEmpty } from '../../../../common';
import {
  isAndroid,
  mainBgColorLightGray,
  splitLineColorLightGray,
  px2dp,
  screenHeight,
  screenWidth,
  mainBgColorWhite,
  fontColorBlack,
  fontColorCoffee
} from '../../../../common/styles';
import HeadTabs from '../../../../components/HeadTabs';
import ReleaseSourceDot from './components/release-source-dot';
import XmList from '../../../../components/XmList';
import supply from '../../../../api/supply';
import LogisticsItem from './components/LogisticsItem';
import Picker from '../../../../common/picker';
import user from '../../../../api/user';

const tabSources = [
  {
    tab: '全部',
    type: ''
  }, {
    tab: '待签约',
    type: 1
  }, {
    tab: '已取消',
    type: 3
  }, {
    tab: '已过期',
    type: 4
  }
];

const tabContract = [
  {
    tab: '全部',
    type: ''
  }, {
    tab: '进行中',
    type: 1
  }, {
    tab: '已完成',
    type: 2
  }, {
    tab: '已到期',
    type: 3
  }
];

/**
 *
 * @author kanglang
 * @description 我的货源
 * @createDate 2020/8/26
 *
 */
export default class Source extends React.Component {
  static navigationOptions = () => ({
    title: '货源',
    tabBarIcon: ({ focused }) => (
      <Image
        source={focused ? iconWlSource : iconWlSourceGray}
        style={{ width: 24, height: 24 }}
      />
    ),
  });

  constructor(props) {
    super(props);
    this.state = {
      pageNo: 1,
      pageSize: 10,
      hasMorePage: false,
      isLoading: false,
      logisticsList: [],
      showFoot: 1, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
      act: 1,
      statusSource: '',
      statusContract: '',

      params: {
        appSearchText: '', // app搜索框
        companyCustId: '', // 签约方法人id 前端不传
        consignorType: '', // 货主类型
        contractNo: '', // 合同编号
        contractStatus: '', // 合同状态 1进行中 2完成 3到期
        custId: '', // 货主ID
        custMobile: '', // 货主电话
        custName: '', // 货主
        endAddress: '', // 终点
        goodsTypeName: '', // 货物名称
        pageNo: 1,
        pageSize: 10,
        queryType: 1, // 1查询货源 2查询合同
        sourceCode: '', // 货源编号
        startAddress: '', // 起点
        status: '', // 货源状态 1.待签约 2.已签约 3已取消 4已过期 -1.禁用
        unitList: []
      },

      /* 选择当前用户类型 */
      consignorType: 0, // 货主类型
      custId: '', // 货主ID//个人取个人ID
      custType: 1, // 客户类型
      custIdDataList: [], // 货主ID列表
      custName: '', // 公司名字，个人传个人名字
      consignorTypeDataList: [], // 货主类型列表
      shouldShowData: false, // 是否获取到用户的类型
      /* end */
    };
  }

  componentDidMount() {
    this.getUnitList().then(res => {
      if (res.success) {
        // 查询列表数据
        InteractionManager.runAfterInteractions(() => {
          this.loadData();
        });
      }
    });
    this.listenser = DeviceEventEmitter.addListener('UPDATE_LOGISTICS', () => {
      InteractionManager.runAfterInteractions(() => {
        this.loadData();
      });
      // const { shouldShowData } = this.state;
      // // 添加用户信息判断
      // if(shouldShowData){
      //   let params = Object.assign(this.state.params,{pageNo: 1})
      //   this.setState({logisticsList: []},()=>{
      //     InteractionManager.runAfterInteractions(() => {
      //       this.getUnitList().then(res=>{
      //         this.loadData();
      //       })
      //     });
      //   })
      // }else{
      //   // 返回
      //   msg.emit('app:tip', { text: "获取用户信息失败" });
      //   setTimeout(() => {
      //     msg.emit('router: back');
      //   }, 1500);
      // }
    });
  }

  componentWillUnmount() {
    this.listenser.remove();
  }

  // 获取单位
  getUnitList = () => {
    return new Promise((resolve) => {
      supply.unitList().then(res => {
        this.setState({ unitList: res.data }, () => {
          resolve(res);
        });
      });
    });
  }

  // 下拉刷新
  loadData() {
    // const { shouldShowData } = this.state;
    // if(shouldShowData){
    let params = Object.assign(this.state.params, { pageNo: 1 });
    this.setState({
      isLoading: true,
      params,
      logisticsList: []
    }, () => {
      console.log('this.state.logisticsList');
      console.log(this.state.logisticsList);
      this.partLoadData('dropdown');
    });
    // }else{
    //   msg.emit('app:tip', { text: "获取用户信息失败" });
    // }
  }

  // 上拉加载更多
  LoadMore = () => {
    const { shouldShowData } = this.state;
    // if(shouldShowData){
    this.setState({ showFoot: 2 });
    this.partLoadData('pullMore');
    // }else{
    //   msg.emit('app:tip', { text: "获取用户信息失败" });
    // }
  }

  partLoadData = (type) => {
    const { queryType } = this.state.params;
    const { statusSource, statusContract } = this.state;
    supply.pageGoodsSource(this.state.params).then(res => {
      if (res.success) {
        let { logisticsList } = this.state;
        const newList = res.data && res.data.records;
        if (res.data.total == 0) {
          this.setState({
            isLoading: false,
            hasMorePage: false,
            showFoot: 0
          });
          return;
        }
        if (newList.length <= 0) {
          this.setState({
            isLoading: false,
            hasMorePage: false,
            showFoot: 1
          });
          return;
        }

        if (type == 'dropdown') {
          logisticsList = newList.concat(logisticsList);
          this.setState({ isLoading: false });
        } else if (type == 'pullMore') {
          logisticsList = logisticsList.concat(newList);
          this.setState({ hasMorePage: true, isLoading: false });
        }
        let params = Object.assign(this.state.params, { pageNo: this.state.params.pageNo + 1 });

        this.setState({
          hasMorePage: true,
          params,
          logisticsList
        });

        if (res.data.result.length <= this.state.pageSize) {
          this.setState({
            isLoading: false,
            hasMorePage: false,
            showFoot: 1
          });
        }
      } else {
        this.setState({
          isLoading: false,
          hasMorePage: false,
          showFoot: 0
        });
        msg.emit('app:tip', { text: '获取数据失败' });
      }
    }).catch(err => {
      this.setState({
        isLoading: false,
        hasMorePage: false,
        showFoot: 0
      });
    });
  }

  // 修改信息
  editunc = (item) => {
    msg.emit('router: goToNext', {
      routeName: 'ReleaseSource',
      id: item.id,
      type: 'edit'
    });
  }

  // 快速重发
  reSendfunc = (item) => {
    msg.emit('router: goToNext', {
      routeName: 'ReleaseSource',
      id: item.id,
      type: 'resend'
    });
  }

  // 右边按钮
  handleFunc = (item) => {
    console.log('右边按钮--->', item);
    const { params, unitList } = this.state;
    if (params.queryType == 1) {
      if (item.status == 1) {
        // 修改信息
        this.editunc(item);
      } else if (item.status == 3 || item.status == 4) {
        // 快速重发
        this.reSendfunc(item);
      }
    } else if (params.queryType == 2) {
      if (item.contractStatus == 1) {
        // 创建订单
        msg.emit('router: goToNext', {
          routeName: 'CreatOrder',
          item: item,
          unitList: unitList
        });
      } else if (item.contractStatus == 2 || item.contractStatus == 3) {
        // 快速重发
        this.reSendfunc(item);
      }
    }
  }

  // 取消按钮
  cancelFunc = (item) => {
    const { params } = this.state;
    NativeModules.WindowModule.showWindow({ content: '确定要取消吗？', leftStr: '暂不取消' }, (e) => {
      if (e == 1) {
        if (params.queryType == 1) {
          // 取消货源
          supply.cancelGoodsSource(item.id).then(res => {
            if (res.success) {
              this.loadData();
            } else {
              NativeModules.WindowModule.showWindow({ content: '取消失败,请稍后重试', onlyRightBtn: '1' }, (e) => { });
            }
          });
        } else if (params.queryType == 2) {
          // 取消合同
          supply.cancelContaract(item.id).then(res => {
            if (res.success) {
              // msg.emit('router: back');
              this.loadData();
            } else {
              NativeModules.WindowModule.showWindow({ content: '取消失败,请稍后重试', onlyRightBtn: '1' }, (e) => { });
            }
          });
        }
      }
    });
  }

  // 货源详情
  goodsDetails(item) {
    const { act } = this.state;
    console.log('item->', item);
    msg.emit('router: goToNext', {
      routeName: 'LogisticsDetail',
      title: act === 1 ? '货源详情' : '合同详情',
      id: item.id,
      queryType: act,
      status: item.status,
      item: item
    });
  }

  render() {
    const { logisticsList, isLoading, hasMorePage, showFoot, act, statusSource, statusContract, params, unitList } = this.state;
    const renderItem = ({ item }) => {
      return <LogisticsItem
        logisticsObj={item}
        unitList={unitList}
        queryType={params.queryType}
        handleFunc={() => this.handleFunc(item)}
        goodsDetails={() => this.goodsDetails(item)}
        cancelFunc={() => this.cancelFunc(item)}
        isfavorite
      />;
    };
    return (
      // <SafeAreaView style={{ flex: 1, alignItems: 'center' }}>
      <SafeAreaView>
        <Header
          renderTitle={() => this._renderTitle(act)}
          renderLeft={() => this._renderLeft()}
          renderRight={() => this._renderRight()}
        />
        {
          act === 1 ?
            (
              <HeadTabs
                tabSources={tabSources}
                changeStatus={(type) => this.changeStatusSource(type)}
                status={statusSource}
              />
            )
            :
            (
              <HeadTabs
                tabSources={tabContract}
                changeStatus={(type) => this.changeStatusContract(type)}
                status={statusContract}
              />
            )
        }

        <View style={styles.container}>
          <View style={styles.listWrap}>
            <XmList
              sources={logisticsList}
              renderItem={renderItem}
              isLoading={isLoading}
              onDropdownRefresh={() => this.loadData()}
              hasMorePage={hasMorePage}
              onPullUpMore={this.LoadMore}
              singleKey={item => item.id}
              showFoot={showFoot}
              customEmptyView={
                <XMEmpty
                  emptyImg={empty01}
                  boxStyle={{ marginTop: px2dp(380) }}
                  desc='暂无数据'
                />
              }
            />
          </View>
        </View>
        {/* 去发货 */}
        <ReleaseSourceDot style={{ positon: 'absolute', bottom: px2dp(280) }} />
      </SafeAreaView>
    );
  }

  changeTab = (act) => {
    // queryType 1查询货源 2查询合同
    let params = Object.assign(this.state.params, { queryType: act, pageNo: 1, status: '', contractStatus: '' });
    this.setState({
      statusSource: '',
      statusContract: '',
      productOrderList: [],
      params,
      act
    }, () => {
      this.loadData();
    });
    // this.setState({act})
  }

  changeStatusSource = (statusSource) => {
    let params = Object.assign(this.state.params, { status: statusSource, pageNo: 1, contractStatus: '' });
    this.setState({
      statusSource,
      productOrderList: [],
      params
    }, () => {
      InteractionManager.runAfterInteractions(() => {
        this.loadData();
      });
    });
  }

  changeStatusContract = (statusContract) => {
    let params = Object.assign(this.state.params, { contractStatus: statusContract, pageNo: 1, status: '' });
    this.setState({
      statusContract,
      productOrderList: [],
      params
    }, () => {
      InteractionManager.runAfterInteractions(() => {
        this.loadData();
      });
    });
  }

  _renderTitle = (act) => {
    return (
      <View style={styles.titleWrap}>
        <TouchableOpacity onPress={() => this.changeTab(1)}><Text style={[styles.tab, act === 1 ? styles.act : '']}>货源</Text></TouchableOpacity>
        <TouchableOpacity onPress={() => this.changeTab(2)}><Text style={[styles.tab, act === 2 ? styles.act : '']}>合同</Text></TouchableOpacity>
      </View>
    );
  }

  _renderLeft = () => {
    return (
      <TouchableOpacity
        activeOpacity={0.8}
        style={isAndroid ? { paddingVertical: px2dp(14), paddingHorizontal: px2dp(40) } :
          { paddingVertical: px2dp(14), paddingRight: px2dp(40) }}
        onPress={() => {
          msg.emit('router: back');
        }}
      >
        <BackImage />
      </TouchableOpacity>
    );
  }

  _renderRight = () => {
    const { act } = this.state;
    if (act === 1) {
      return (
        <TouchableOpacity
          activeOpacity={0.8}
          style={styles.titRigth}
          onPress={() => this.toSendGoods()}
        >
          <Image source={iconWlAdd} style={styles.titRightIcon} />
          <Text style={styles.addText}>新增</Text>
        </TouchableOpacity>
      );
    }
    return <></>;
  }

  toSendGoods = () => {
    msg.emit('router: refreshRoute', {
      routeName: 'ReleaseSource',
    });
    msg.emit('router: goToNext', {
      routeName: 'ReleaseSource',
      // id: this.state.detail.id
    });
  }
}

const styles = StyleSheet.create({
  container: {
    height: '100%',
    width: '100%',
    backgroundColor: mainBgColorLightGray,
    alignItems: 'center',
    paddingBottom: px2dp(360)
  },
  addText: {
    marginHorizontal: 6,
    color: fontColorCoffee
  },
  titRigth: {
    marginRight: 14,
    flexDirection: 'row',
    alignContent: 'center',
    alignItems: 'center',
    height: px2dp(32 * 2)
  },
  titRightIcon: {
    width: px2dp(28),
    height: px2dp(28)
  },
  titleWrap: {
    flexDirection: 'row',
    justifyContent: 'center',
    backgroundColor: splitLineColorLightGray,
    padding: px2dp(6),
    borderRadius: px2dp(12)
  },
  tab: {
    width: px2dp(154),
    height: px2dp(52),
    lineHeight: px2dp(52),
    justifyContent: 'center',
    alignItems: 'center',
    textAlign: 'center',
    borderRadius: px2dp(8),
    color: '#9D9A95'
  },
  act: {
    backgroundColor: mainBgColorWhite,
    color: fontColorBlack
  },
  headerLeft: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  headerWrap: {
    backgroundColor: '#ffffff',
    borderColor: '#e5e5e5',
    ..._.ifIphoneX({ top: 40 }, isAndroid ? { top: 0 } : { top: 20 })
  },
  headerLeft: {
    flexDirection: 'row',
    alignItems: 'center',
    color: '#999896'
  },
  contentPart: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  listWrap: {
    width: '100%'
  },
  sendBtn: {
    position: 'absolute',
    bottom: px2dp(40) * 2,
    width: screenWidth,
    height: px2dp(45) * 2,
    backgroundColor: 'transparent',
    justifyContent: 'center',
    alignItems: 'center'
  },
  backImg: {
    width: px2dp(36),
    height: px2dp(36),
    marginLeft: px2dp(24),
  },
});
